package org.amphiprion.montrictracv4.db.adapter;

import java.util.List;

import org.amphiprion.montrictracv4.R;
import org.amphiprion.montrictracv4.db.model.Search;
import org.amphiprion.montrictracv4.fragment.SearchListFragment;

import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class SearchListAdapter extends ArrayAdapter<Search> implements View.OnClickListener {

	FragmentActivity context;
	int layoutResourceId;
	List<Search> data = null;
	SearchListFragment searchListFragment;

	public SearchListAdapter(FragmentActivity paramFragmentActivity, SearchListFragment searchListFragment, int layoutResourceId, List<Search> data) {
		super(paramFragmentActivity, layoutResourceId, data);
		this.layoutResourceId = layoutResourceId;
		this.searchListFragment = searchListFragment;
		this.context = paramFragmentActivity;
		this.data = data;
	}

	public void add(int position, Search search) {
		data.add(position, search);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		ItemHolder holder = null;

		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);

			holder = new ItemHolder();
			holder.imgEdit = (ImageView) row.findViewById(R.id.imgEdit);
			holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);
			holder.imgEdit.setOnClickListener(this);
			row.setTag(holder);
		} else {
			holder = (ItemHolder) row.getTag();
		}

		Search item = data.get(position);
		holder.imgEdit.setTag(item);
		holder.txtTitle.setText(item.name);

		return row;
	}

	static class ItemHolder {
		ImageView imgEdit;
		TextView txtTitle;
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.imgEdit) {
			Search search = ((Search) v.getTag());
			searchListFragment.editSearch(search.getId());
		}
	}
}
